package dubbo.learn.transport.mina;

import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class MinaLengthFieldPrepender implements ProtocolEncoder {

    public byte[] unsignedShortToByte2(int s) {
        byte[] targets = new byte[2];
        targets[0] = (byte) (s >> 8 & 0xFF);
        targets[1] = (byte) (s & 0xFF);
        return targets;
    }

    @Override
    public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception {
        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);
        String message = (String) msg;
        byte[] datas = message.getBytes("utf-8");
        int length = datas.length;
        buffer.writeBytes(unsignedShortToByte2(length));
        buffer.writeBytes(datas);
        out.write(ByteBuffer.wrap(buffer.toByteBuffer()));
        out.flush();
    }

    @Override
    public void dispose(IoSession session) throws Exception {

    }
}
